<template>
    <el-dialog :title="title" :visible.sync="visible" width="560px" append-to-body :close-on-click-modal="false">
        <BaseForm2
            ref="form"
            label-position="right"
            label-width="86px"
            :fields="fields"
            :text-model="textModel"
            :data="form"
            size="medium"
            @updateValue="updateEvent"
        ></BaseForm2>
        <div slot="footer" class="dialog-footer">
            <BaseButton :loading="submitLoading" @click="submitForm">保 存</BaseButton>
            <BaseButton type="recond" @click="cancel">取 消</BaseButton>
        </div>
    </el-dialog>
</template>

<script>
import BaseForm2 from '@/components/BaseForm2'
import { DirectionOptions } from '@/config/constants'
import { LineHighwayModel, ManagementOfficeModel, MaintSchemeModel } from '@/models'
import { RoadTypeOptions } from '@/views/technical-evaluation/constants'
import { TechnologyLevelOptions, AADTOptions } from '@/views/auxiliary-decision/constants'

export default {
    name: 'SchemeSaveOrUpdate',
    components: {
        BaseForm2
    },
    data() {
        return {
            oldSchemeName: '',
            type: 'add',
            model: new MaintSchemeModel(),
            lineHighwayModel: new LineHighwayModel(),
            managementOfficeModel: new ManagementOfficeModel(),
            title: '添加养护方案',
            visible: false,
            submitLoading: false,
            // 表单参数
            form: {},
            schemeList: [],
            id: '',
            textModel: false,
            fields: [
                {
                    label: '',
                    children: [
                        {
                            options: [],
                            key: 'highwayCode',
                            label: '公路',
                            type: 'normal-select',
                            span: 24,
                            rules: [{ required: true, message: '必填项', trigger: ['change'] }]
                        },
                        {
                            options: [],
                            key: 'orgName',
                            valueKey: 'label',
                            label: '管养单位',
                            type: 'normal-select',
                            span: 24,
                            filterable: true,
                            rules: [{ required: true, message: '必填项', trigger: ['change'] }]
                        },
                        {
                            key: 'schemeName',
                            label: '方案名称',
                            type: 'input',
                            span: 24,
                            disableDefault: true,
                            rules: [
                                { required: true, message: '必填项', trigger: ['blur'] },
                                { validator: this.validUnique, trigger: ['change', 'blur'] }
                            ]
                        },
                        {
                            options: RoadTypeOptions,
                            key: 'pavementType',
                            valueKey: 'label',
                            label: '路面类型',
                            type: 'normal-select',
                            span: 24,
                            placeholder: '请选择',
                            rules: [{ required: true, message: '必填项', trigger: ['change'] }]
                        },
                        {
                            options: TechnologyLevelOptions,
                            key: 'roadType',
                            valueKey: 'label',
                            label: '技术等级',
                            type: 'normal-select',
                            span: 24,
                            placeholder: '请选择',
                            rules: [{ required: true, message: '必填项', trigger: ['change'] }]
                        },
                        {
                            options: AADTOptions,
                            key: 'aadt',
                            label: 'AADT',
                            type: 'normal-select',
                            span: 24,
                            placeholder: '请选择',
                            rules: [{ required: true, message: '必填项', trigger: ['change'] }]
                        }
                    ]
                }
            ]
        }
    },
    created() {
        this.getHighwayList()
        this.getManagementOfficeList()
    },
    methods: {
        updateEvent(data) {
            if (data.highwayCode) {
                const name = (this.fields[0].children[0].options.find((item) => item.value === data.highwayCode) || {}).name
                this.form.highwayName = name
                this.$nextTick(() => {
                    this.$refs.form.updateFormData({ schemeName: name + '养护方案' })
                })
            }
        },
        validUnique(rule, value, callback) {
            let uniqueArr = []
            if (this.type === 'add') {
                uniqueArr = this.schemeList
            } else { // 编辑 
                uniqueArr = this.schemeList.filter(item => item.schemeName !== this.oldSchemeName) 
            }
            if (uniqueArr.find((item) => item.schemeName === value)) {
                callback(new Error('方案名称已存在'))
            } else {
                callback()
            }
        },
        getHighwayList() {
            this.lineHighwayModel.getList({}, { pageNo: 1, pageSize: 10000 }).then((res) => {
                const list = (res.list || []).map((item) => {
                    return {
                        label: item.name + '/' + item.code,
                        value: item.code,
                        name: item.name
                    }
                })
                list.length > 0 && this.$set(this.fields[0].children[0], 'options', list)
            })
        },
        // 获取管理处列表，作为下拉选项
        getManagementOfficeList() {
            this.managementOfficeModel.getList({}, { pageNo: 1, pageSize: 10000 }).then((res) => {
                const list = (res.list || []).map((item) => {
                    return {
                        value: item.id,
                        label: item.name
                    }
                })
                list.length > 0 && this.$set(this.fields[0].children[1], 'options', list)
            })
        },
        // 取消按钮
        cancel() {
            this.visible = false
        },
        open(options = {}) {
            const { type, item = {}, schemeList } = options
            this.type = type
            this.schemeList = schemeList
            this.id = item.id || null
            this.visible = true
            this.$nextTick(() => {
                if (type === 'add') {
                    this.title = '添加养护方案'
                } else {
                    this.title = '编辑养护方案'
                    this.form = { ...item }
                    this.oldSchemeName = item.schemeName
                }
                this.$refs['form'].resetFields()
            })
        },
        submitForm() {
            this.$refs['form'].validate((valid, res) => {
                if (valid) {
                    console.log(res)
                    res.highwayName = this.form.highwayName
                    this.submitLoading = true
                    this.id && (res.id = this.id)
                    this.model
                        .saveOrUpdate(res)
                        .then(() => {
                            this.$message({
                                type: 'success',
                                message: '操作成功！',
                                duration: 500,
                                onClose: () => {
                                    this.visible = false
                                    this.$emit('success', res)
                                }
                            })
                        })
                        .finally(() => {
                            this.submitLoading = false
                        })
                } else {
                    this.$message.error('校验失败！')
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.w-300 {
    width: 300px;
}
</style>
